﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using System.Windows.Media.Imaging;
using SLLottery.LotterySrv;
using SLLottery.Common;
using System.Collections.ObjectModel;
using System.Windows.Data;
using System.Globalization;
using System.Windows.Threading;
using System.Threading;
namespace SLLottery.Controls
{
    public partial class KaijiangContainer : UserControl
    {
        private LotterySrv.LotteryServiceClient _srv;
        //private DispatcherTimer timer_fendan = new DispatcherTimer();
        private DispatcherTimer timer_kaijiang = new DispatcherTimer();
        private DispatcherTimer timer_getLotteryNum = new DispatcherTimer();
        private DateTime CurrentDateTime;
        private DateTime LastRefreshTime;
        private string LastIssueNo = string.Empty;
        private string currentIssueNo = string.Empty;
        public List<LotteryNumsInfo> DataSource
        {
            get { return (List<LotteryNumsInfo>)this.LotteryNumsGrid.ItemsSource; }
            set
            {
                this.LotteryNumsGrid.ItemsSource = value;
            }
        }
        public KaijiangContainer()
        {
            InitializeComponent();
            _srv = WcfProxy.GetProxy;
            timer_kaijiang.Interval = TimeSpan.FromSeconds(1);
            timer_kaijiang.Tick += new EventHandler(timer_kaijiang_Tick);
            MainPage.kaijiang_timer = timer_kaijiang;
            _srv.GetCurrenIssuNoCompleted += new EventHandler<GetCurrenIssuNoCompletedEventArgs>(_srv_GetCurrenIssuNoCompleted);
            _srv.GetLastLotteryNumCompleted += new EventHandler<GetLastLotteryNumCompletedEventArgs>(_srv_GetLastLotteryNumCompleted);
            _srv.GetRecentlyLotteryNumCompleted += new EventHandler<GetRecentlyLotteryNumCompletedEventArgs>(_srv_GetRecentlyLotteryNumCompleted);
            this.LotteryNumsGrid.LoadingRow += new EventHandler<DataGridRowEventArgs>(LotteryNumsGrid_LoadingRow);
            _srv.GetPfLoss_YKCompleted += _srvProxy_GetPfLoss_YKCompleted;
            _srv.GetOddsCompleted += srv_GetOddsCompleted;
        }

        void LotteryNumsGrid_LoadingRow(object sender, DataGridRowEventArgs e)
        {
            LotteryNumsInfo data = DataSource[e.Row.GetIndex()];
            int LastNum = 0;
            if (data.LotteryNums.IndexOf(",") > -1)
            {
                string[] nums = data.LotteryNums.Split(',');
                LastNum = Convert.ToInt32(nums[nums.Length - 1]);
                if (LastNum > 8)
                    data.Size = "大";
                else
                    data.Size = "小";
            }
            else
            {
                LastNum = Convert.ToInt32(data.LotteryNums.Substring(data.LotteryNums.Length - 1, 1));
                if (LastNum > 4)
                    data.Size = "大";
                else
                    data.Size = "小";
            }
            if (LastNum % 2 != 0)
                data.Parity = "单";
            else
                data.Parity = "双";
          
        }
        private BallSize BallSize = BallSize.Big;
        private string lotteryNums = string.Empty;
        public void CreateElement(string LotteryNum, Controls.BallSize size)
        {
            BallSize = size;
            lotteryNums = LotteryNum;
            _srv.GetCurrenIssuNoAsync((int)MainPage.lotteryType);
            _srv.GetLastLotteryNumAsync((int)MainPage.lotteryType);
        }
        void _srv_GetLastLotteryNumCompleted(object sender, GetLastLotteryNumCompletedEventArgs e)
        {
            if (e.Result.IssueNo.Length > 7)
                this.tb_Last_IssueNo.Text = e.Result.IssueNo.Length > 7 ? e.Result.IssueNo.Substring(2, e.Result.IssueNo.Length - 2) : e.Result.IssueNo;
            else
                this.tb_Last_IssueNo.Text = e.Result.IssueNo;
            LastIssueNo = e.Result.IssueNo;
            App.Session[Constant.LASTISSUENO_SESSION] = e.Result;
            border_IssueNo.Visibility = Visibility.Visible;
        }
        void _srv_GetCurrenIssuNoCompleted(object sender, GetCurrenIssuNoCompletedEventArgs e)
        {
            LastRefreshTime = DateTime.Now;
            if (e.Result == null)
                return;
            this.tb_current_IssueNo.Text = e.Result.IssueNo.Length > 7 ? e.Result.IssueNo.Substring(2, e.Result.IssueNo.Length - 2) : e.Result.IssueNo;
            currentIssueNo = e.Result.IssueNo;
            //if (MainPage.TouzhuControl != null)
            //    MainPage.TouzhuControl.btBet.IsEnabled = true;
            if (MainPage.lotteryTypeAll == LotteryType.NSSC//绑定逆向赔率
                || MainPage.lotteryTypeAll == LotteryType.N3D
                || MainPage.lotteryTypeAll == LotteryType.NSSQ)
                _srv.GetOddsAsync(MainPage.playType, MainPage.playTypeRadio, currentIssueNo);
            App.Session[Constant.CURRENTISSUENO_SESSION] = e.Result;
            LotteryServiceClient srv = WcfProxy.GetProxy;
            //if (MainPage.TouzhuControl != null)
            //    MainPage.TouzhuControl.btBet.IsEnabled = false;
            srv.GetServerCurrentTimeAsync();
            srv.GetServerCurrentTimeCompleted += (s, er) =>
            {
                CurrentDateTime = er.Result.AddSeconds(-40);
                LotteryNumsInfo currentNums = App.Session[Constant.CURRENTISSUENO_SESSION] as LotteryNumsInfo;
                TimeSpan ts = (currentNums.LotteryDate - CurrentDateTime);
                if (ts.TotalSeconds <= 0)
                {
                    MainPage.IsFengDan = true;
                    timer_kaijiang.Interval = TimeSpan.FromSeconds(5);
                    tb_kaijiang.Text = "正在开奖";
                    tb_Last_IssueNo.Text = currentNums.IssueNo.Length > 7 ? currentNums.IssueNo.Substring(2, currentNums.IssueNo.Length - 2) : currentNums.IssueNo;
                    gridLoading.Visibility = Visibility.Visible;
                    border_Time.Visibility = Visibility.Collapsed;
                    border_Nums.Visibility = Visibility.Collapsed;
                }
                else
                {
                    MainPage.IsFengDan = false;
                    timer_kaijiang.Interval = TimeSpan.FromSeconds(1);
                    KaijiangBalls.size = BallSize;
                    KaijiangBalls.LotteryNum = lotteryNums;//加载开奖结果（大球）
                    //gridLoading.Visibility = Visibility.Collapsed;
                    //border_Time.Visibility = Visibility.Visible;
                    //border_Nums.Visibility = Visibility.Visible;
                }
                if (timer_kaijiang.IsEnabled == false)
                {
                    timer_kaijiang_Tick(null, null);
                    timer_kaijiang.Start();
                }
                SetLotteryTypeStatus(true);
            };
        }
        //void timer_fendan_Tick(object sender, EventArgs e)
        //{
        //    if (App.Session.Count == 0)
        //        return;
        //    if (MainPage.TouzhuControl != null)
        //    {
        //        if (timer_getLotteryNum.IsEnabled)
        //            timer_getLotteryNum.Stop();
        //        if (timer_kaijiang.IsEnabled)
        //            timer_kaijiang.Stop();
        //        MainPage.TouzhuControl.btBet.IsEnabled = true;
        //    }
        //    if (App.Session[Constant.CURRENTISSUENO_SESSION] == null)
        //    {
        //        timer_fendan.Stop();
        //        timer_kaijiang.Stop();
        //        timer_getLotteryNum.Stop();
        //        return;
        //    }
        //    LotteryNumsInfo current = App.Session[Constant.CURRENTISSUENO_SESSION] as LotteryNumsInfo;
        //    TimeSpan ts = (current.LotteryDate - CurrentDateTime);
        //    if(JudgeFengdan(ts))
        //    {
        //        if (MainPage.TouzhuControl != null)
        //        {
        //            MainPage.TouzhuControl.btBet.IsEnabled = false;
        //        }
        //        tb_fendan.Text = "距离开奖时间还有";
        //        timer_fendan.Stop();
        //        //timer_kaijiang_Tick(null, null);
        //        timer_kaijiang.Start();
        //        return;
        //    }
        //    //双色球提前一个半小时即8点封单，3D是8点封单封单，时时彩提前30秒封单时间
        //    SetFengdanTimes(current.LotteryDate, ts);
        //    CurrentDateTime = CurrentDateTime.AddSeconds(1);
        //}
        public void SetLotteryTypeStatus(bool status)
        {

            foreach (RadioButton rb in MainPage.stkP.Children)
            {
                if (!rb.IsChecked.Value)
                {
                    rb.IsEnabled = status;
                }
            }
            foreach (RadioButton rb in MainPage.stkR.Children)
            {
                if (!rb.IsChecked.Value)
                {
                    rb.IsEnabled = status;
                }
            }
        }
        void SetFengdanTimes(DateTime lotteryTime, TimeSpan ts)
        {
            if (MainPage.lotteryType == LotteryType.NSSC
                || MainPage.lotteryType == LotteryType.SSC)
            {
                ts = (lotteryTime.AddMinutes(-1) - CurrentDateTime);
            }
            else if (MainPage.lotteryType == LotteryType._3D
                || MainPage.lotteryType == LotteryType.N3D)
            {
                ts = (lotteryTime.AddMinutes(-30) - CurrentDateTime);
            }
            else
            {
                ts = (lotteryTime.AddMinutes(-90) - CurrentDateTime);
            }
            double hours = ts.Days * 24 + ts.Hours;
            this.tb_Time.Text = (hours == 0 ? "" : (
                            (hours.ToString().Length == 1 ? ("0" + hours.ToString()) : hours.ToString()) + ":"))
                            + (ts.Minutes==0?"":(
                            (ts.Minutes.ToString().Length == 1 ? ("0" + ts.Minutes.ToString()) : ts.Minutes.ToString()) + ":"))
                            + (ts.Seconds.ToString().Length == 1 ? ("0" + ts.Seconds.ToString()) : ts.Seconds.ToString());
        }
        void SetKaijiangTimes(DateTime lotteryTime, TimeSpan ts)
        {
            this.tb_Time.Text = "";
            ts = (lotteryTime - CurrentDateTime);
            double hours = ts.Days * 24 + ts.Hours;
            this.tb_Time.Text = (hours == 0 ? "" : (
                            (hours.ToString().Length == 1 ? ("0" + hours.ToString()) : hours.ToString()) + ":"))
                            + (ts.Minutes == 0 ? "" : (
                            ts.Minutes.ToString().Length == 1 ? ("0" + ts.Minutes.ToString()) : ts.Minutes.ToString()) + ":")
                            + (ts.Seconds.ToString().Length == 1 ? ("0" + ts.Seconds.ToString()) : ts.Seconds.ToString());
        }
        bool JudgeFengdan(TimeSpan ts)
        {
            if (MainPage.lotteryType == LotteryType.NSSC
                || MainPage.lotteryType == LotteryType.SSC)
            {
                if (ts.TotalSeconds < 60)
                    return true;
                else
                    return false;
            }
            else if (MainPage.lotteryType == LotteryType._3D
                || MainPage.lotteryType == LotteryType.N3D)
            {
                if (ts.TotalSeconds < 30*60)
                    return true;
                else
                    return false;
            }
            else
            {
                if (ts.TotalSeconds < 90*60)
                    return true;
                else
                    return false;
            }
        }
        void timer_kaijiang_Tick(object sender, EventArgs e)
        {
            if (App.Session.Count == 0 || App.Session[Constant.CURRENTISSUENO_SESSION] == null)
                return;
            LotteryNumsInfo current = App.Session[Constant.CURRENTISSUENO_SESSION] as LotteryNumsInfo;
            TimeSpan ts = (current.LotteryDate - CurrentDateTime);
            if (ts.TotalSeconds < 1)
            {
                MainPage.IsFengDan = true;
                MainPage.kaijiangState = 3;
                if (MainPage.TouzhuControl != null)
                    MainPage.TouzhuControl.btBet.IsEnabled = false;
                if (MainPage.rateGrids != null)
                {
                    foreach (RateGrid rg in MainPage.rateGrids)
                    {
                        if (!rg.isFendan)
                            rg.FengDan();
                    }
                }
                tb_kaijiang.Text = "正在开奖";
                tb_Last_IssueNo.Text = current.IssueNo;
                gridLoading.Visibility = Visibility.Visible;
                border_Time.Visibility = Visibility.Collapsed;
                border_Nums.Visibility = Visibility.Collapsed;
                timer_kaijiang.Stop();
                timer_kaijiang.Interval = TimeSpan.FromSeconds(5);
                _srv.GetRecentlyLotteryNumAsync((int)MainPage.lotteryType);
            }
            else
            {
                MainPage.kaijiangState = 1;
                tb_kaijiang.Text = "开奖结果";
                if (LastIssueNo.Length > 7)
                    this.tb_Last_IssueNo.Text = LastIssueNo.Length > 7 ? LastIssueNo.Substring(2, LastIssueNo.Length - 2) : LastIssueNo;
                else
                    this.tb_Last_IssueNo.Text = LastIssueNo;
                gridLoading.Visibility = Visibility.Collapsed;
                border_Time.Visibility = Visibility.Visible;
                border_Nums.Visibility = Visibility.Visible;
                timer_kaijiang.Interval = TimeSpan.FromSeconds(1);
                //双色球提前一个半小时即8点封单，3D是8点封单封单，时时彩提前30秒封单时间
                if (!JudgeFengdan(ts))
                {
                    MainPage.IsFengDan = false;
                    if (LastRefreshTime == null)
                        LastRefreshTime = DateTime.Now;
                    else
                        RefreshRateData();
                    if (MainPage.TouzhuControl != null)
                        MainPage.TouzhuControl.btBet.IsEnabled = true;
                    tb_fendan.Text = "距离封单时间还有";
                    SetFengdanTimes(current.LotteryDate, ts);
                    CurrentDateTime = CurrentDateTime.AddSeconds(1);
                }
                else
                {
                    MainPage.IsFengDan = true;
                    MainPage.kaijiangState = 2;
                    if (MainPage.TouzhuControl != null)
                        MainPage.TouzhuControl.btBet.IsEnabled = false;
                    tb_fendan.Text = "距离开奖时间还有";
                    SetKaijiangTimes(current.LotteryDate, ts);
                    if (MainPage.rateGrids != null)
                    {
                        foreach (RateGrid rg in MainPage.rateGrids)
                        {
                            rg.FengDan();
                        }
                    }
                    CurrentDateTime = CurrentDateTime.AddSeconds(1);
                }
            }
        }
        void RefreshRateData()
        {
            if (MainPage.lotteryTypeAll == LotteryType.NSSC//绑定逆向赔率
                || MainPage.lotteryTypeAll == LotteryType.N3D
                || MainPage.lotteryTypeAll == LotteryType.NSSQ)
            {
                TimeSpan ts = DateTime.Now - LastRefreshTime;
                if (ts.TotalSeconds >= 60)
                {
                    //_srv.GetOddsAsync((int)MainPage.lotteryTypeAll, MainPage.playTypeRadio, currentIssueNo);
                    LastRefreshTime = DateTime.Now;
                }
            }
        }
        void _srv_GetRecentlyLotteryNumCompleted(object sender, GetRecentlyLotteryNumCompletedEventArgs e)
        {
            List<LotteryNumsInfo> list = e.Result.ToList();
            if (App.Session.Count == 0)
                return;
            LotteryNumsInfo current = App.Session[Constant.CURRENTISSUENO_SESSION] as LotteryNumsInfo;
            LotteryNumsInfo result = list.Where(c => c.IssueNo == current.IssueNo).ToList().FirstOrDefault();
            if (result == null)
            {
                timer_kaijiang.Start();
                return;
            }
            else
            {
                //timer_kaijiang.Stop();
                timer_kaijiang.Interval = TimeSpan.FromSeconds(1);
                CreateElement(result.LotteryNums, BallSize);
                tb_kaijiang.Text = "开奖结果";
                gridLoading.Visibility = Visibility.Collapsed;
                border_Time.Visibility = Visibility.Visible;
                border_Nums.Visibility = Visibility.Visible;
                DataSource = list;
                //刷新用户余额、弹出盈亏窗口
                RefreshKJData();
            }
        }
        void srv_GetOddsCompleted(object sender, GetOddsCompletedEventArgs e)
        {
            if (MainPage.rateGrids != null)
            {
                foreach (RateGrid rg in MainPage.rateGrids)
                {
                    rg.DataSource = e.Result.ToList();
                    rg.BindData();
                }
            }
            App.Session[Constant.REVERSEODDS_SESSION] = e.Result.ToList();
        }
        void RefreshKJData()
        {
            LotteryServiceClient srv = WcfProxy.GetProxy;
            srv.GetCapitalInfoAsync(App.Session[Constant.USERNAME_SESSION].ToString());
            srv.GetCapitalInfoCompleted += (s, er) =>
            {
                MainPage.PersonalControl.DataContext = er.Result;
            };
            if (MainPage.mainBet != null)
                MainPage.mainBet.RefreshGrid();
            _srv.GetPfLoss_YKAsync(App.Session[Constant.USERNAME_SESSION].ToString(), (App.Session[Constant.CURRENTISSUENO_SESSION] as LotteryNumsInfo).IssueNo);
        }
        public void _srvProxy_GetPfLoss_YKCompleted(object sender, GetPfLoss_YKCompletedEventArgs e)
        {
            List<PfLossMsg> list = e.Result.ToList();
            if (e.Result.Count > 0)
            {
                if (MainPage.media != null)
                    MainPage.media.Play();
            }
            foreach (PfLossMsg p in list)
            {
                string Content = p.LotteryName + (p.IssueNo.Length > 7 ? p.IssueNo.Substring(2, p.IssueNo.Length - 2) : p.IssueNo) + "期派奖结束\n";
                Content += string.Format("您共有{0}条投注记录\n", p.RecordCount.ToString());
                Content += string.Format("本期净盈亏{0}元", p.ProfitLossMoney.ToString());
                Notify_Add(p.ProfitLossType + "提示", Content, p.ProfitLossTime.ToString("yyyy-MM-dd HH:mm:ss"));
            }
        }
        void Notify_Add(string Title, string Content, string Time)
        {
            Size size = MainPage._layRoot.RenderSize;
            if (MainPage.sp.ActualHeight + 85 >= size.Height)
            {
                return;
            }
            MsgNotify msg = new MsgNotify();
            msg.lbTime.Text = Time;
            msg.lbTitle.Text = Title;
            msg.lbContent.Text = Content;
            MainPage.sp.Children.Add(msg);
            msg.btnClose.MouseLeftButtonDown += (s, e) =>
            {
                MainPage.sp.Children.Remove(msg);
                MainPage._tip.HorizontalOffset = size.Width - 220;
                MainPage._tip.VerticalOffset = size.Height - (MainPage.sp.Children.Count) * 85;
            };
            MainPage._tip.IsOpen = true;
            MainPage._tip.HorizontalOffset = size.Width - 220;
            MainPage._tip.VerticalOffset = size.Height - (MainPage.sp.Children.Count) * 85;
        }
        public void LoadData()
        {
            gridLoading.Visibility = Visibility.Visible;
            border_Time.Visibility = Visibility.Collapsed;
            border_Nums.Visibility = Visibility.Collapsed;
            tb_fendan.Text = "";
            this.tb_Time.Text = "";
            tb_Last_IssueNo.Text = "";
            
            KaijiangBalls.LotteryNum = "";
        }
    }

    public class ImageConverter : IValueConverter
    {
        public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
        {
            if (value.ToString().Length > 5)
            {

            }
            DateTime date = (DateTime)value;
            return date.ToShortDateString();
        }

        public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
        {
            string strValue = value.ToString();
            DateTime resultDateTime;
            if (DateTime.TryParse(strValue, out resultDateTime))
            {
                return resultDateTime;
            }
            return value;
        }
    }
}
